﻿using System;

/*
    We are given an integer number n, a bit value v (v=0 or 1) and a position p.
    Write a sequence of operators (a few lines of C# code) that modifies n to hold the value v at the position p 
    from the binary representation of n while preserving all other bits in n.
 */
class ModifyBitGivenPosition
{
    private static int numberTransform(int number, int position, int value)
    {
        if (value == 1)
        {
            int mask = 1 << position;
            number = number | mask;
        }
        else
        {
            int mask = ~(1 << position);
            number = number & mask;
        }
        Console.WriteLine("The new number is:               "
            + Convert.ToString(number, 2).PadLeft(32, '0'));
        Console.WriteLine(number);
        return number;
    }

    private static int checkForValue(int value)
    {
        while (value != 0 && value != 1)
        {
            Console.WriteLine("Value MUST be 0 or 1 !");
            value = int.Parse(Console.ReadLine());
        }
        return value;
    }

    static void Main()
    {

        Console.WriteLine("The number is: ");
        int number = int.Parse(Console.ReadLine());

        Console.WriteLine("The number is:                   "
            + Convert.ToString(number, 2).PadLeft(32, '0'));

        Console.WriteLine("The position is: ");
        int position = int.Parse(Console.ReadLine());
        Console.WriteLine("The Value is: ");
        int value = int.Parse(Console.ReadLine());

        value = checkForValue(value);


        number = numberTransform(number, position, value);
    }

}